<template>
  <div class="w-full h-full">
    <el-upload ref="upload" v-model:file-list="fileList" :headers="{
      token
    }" :auto-upload="true" :data="data" name="fileUpload" :action="uploadUrl" :limit="limit" multiple
      :on-preview="handlePreview" :on-success="handleSuccess" :on-remove="handleRemove" :before-upload="beforeUpload"
      :before-remove="beforeRemove" :on-exceed="handleExceed">

      <div class="w-full h-full">
        <el-button type="primary">选择文件</el-button>
      </div>

      <template #tip>
        <div class="el-upload__tip" v-if="tip">
          {{ tip }}
        </div>
      </template>
    </el-upload>

  </div>
</template>
<script setup lang="ts">
import { uploadUrl, geturlneeddl, getPicImg } from '@/api/upload'
import { getStorage } from '@/utils/storage'
import { message } from "@/utils/message";
import { genFileId } from 'element-plus'
import type { UploadProps, UploadUserFile, UploadInstance, UploadRawFile } from 'element-plus'
import { ref, withDefaults, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const token = getStorage('token')


interface ispic {
  ispic: string
}

interface Props {
  data?: ispic
  limit?: number
  tip?: string
  modelValue: Array
  type?: string
}

const props = withDefaults(defineProps<Props>(), {
  limit: 1,
  data: () => ({ ispic: '1' }),
  modelValue: () => [],
  tip: '',
  type: 'pdf'
})

const emits = defineEmits(['success', "update:modelValue", "onPreviewFn", "beforeRemoveFn"])


const upload = ref<UploadInstance>()


const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  let url = uploadFile.url ? uploadFile.url : geturlneeddl(uploadFile.response?.data?.result[0].uuid)
  if (props.type === 'pdf') {
    return emits("onPreviewFn", url)
  }



  if (url.startsWith('http')) {
    return window.open(url)
  }


  if (/\.(gif|jpg|jpeg|png)$/i.test(uploadFile.name)) {
    if (!url.startsWith('http')) {
      url = getPicImg(url)
    }
  } else {
    if (!url.startsWith('http')) {
      url = geturlneeddl(url)
    }
  }
  window.open(url)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `超出最大上传量，请先移除再上传`
  )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  emits("beforeRemoveFn")
  // return ElMessageBox.confirm(
  //   `Cancel the transfer of ${uploadFile.name} ?`
  // ).then(
  //   () => true,
  //   () => false
  // )
}

const beforeUpload: UploadProps['beforeUpload'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, 'uploadFile111')
  console.log(uploadFiles, 'uploadFiles222')
  if (props.type === 'pdf') {
    if (uploadFile.type !== 'application/pdf') {
      ElMessageBox.confirm(
        `请上传pdf文件`
      )
      return false
    }
  }

}



function size2Str(size) {
  if (size < 1024) {
    return size + 'B';
  } else if (size >= 1024 && size < Math.pow(1024, 2)) {
    return parseFloat(size / 1024).toFixed(2) + 'KB';
  } else if (size >= Math.pow(1024, 2) && size < Math.pow(1024, 3)) {
    return parseFloat(size / Math.pow(1024, 2)).toFixed(2) + 'MB';
  } else if (size > Math.pow(1024, 3)) {
    return parseFloat(size / Math.pow(1024, 3)).toFixed(2) + 'GB';
  } else {
    return 0 + 'B';
  }
}


const handleSuccess = (response, uploadFile, uploadFiles) => {
  const size = size2Str(uploadFile.size)
  emits("success", size)
}

const fileList = ref<UploadUserFile[]>([...props.modelValue])


// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
//   console.log(uploadFile, uploadFiles)
// }


watch(fileList, newValue => {
  console.log(newValue, 'newValue11')
  if (props.type == 'otherFilter' && newValue[0]?.name) {
    let Q = {
      name: newValue[0]?.name,
      url: newValue[0]?.url ? newValue[0]?.url : geturlneeddl(newValue[0]?.response?.data?.result[0]?.uuid)
    }
    console.log(Q, 'Q')
    emits("update:modelValue", [Q])
  } else {
    emits("update:modelValue", newValue)
  }
}, {
  deep: true
});

</script>